<template>
  <div id="dialogChooseClass">
    <el-dialog
      title="选择分组学员"
      :visible.sync="dialogData.isShow"
      width="1400px"
      @close="closeAddDialog"
    >
      <!-- 顶部搜索框部分 -->
      <div class="search-box">
        <el-form
          ref="ruleForm"
          :inline="true"
          :model="formInline"
          label-width="auto"
          size="small"
        >
          <el-form-item label="分组名称" prop="name">
            <el-input
              v-model="formInline.name"
              multiple
              filterable
              clear
              remote
              reserve-keyword
              placeholder="请输入分组名称"
            >
            </el-input>
          </el-form-item>
          <!-- 输入搜索部分 -->
          <el-form-item label="启用状态" prop="groupStatus">
            <el-select
              v-model="formInline.groupStatus"
              placeholder="请选择启用状态"
              clearable
            >
              <el-option
                v-for="item in stateList"
                :key="item.dictLabel"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计算状态" prop="finalCalculationStatus">
            <el-select
              v-model="formInline.finalCalculationStatus"
              placeholder="请选择计算状态"
              clearable
            >
              <el-option
                v-for="item in calculationStatusList"
                :key="item.dictLabel"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="更新方式" prop="updateMethod">
            <el-select
              v-model="formInline.updateMethod"
              placeholder="请选择更新方式"
              clearable
            >
              <el-option
                v-for="item in updateModeList"
                :key="item.dictLabel"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建人" prop="createdUser">
            <el-select
              v-model="formInline.createdUser"
              placeholder="请选择"
              style="width: 150px"
              clearable filterable
            >
              <el-option
                v-for="item in creaters"
                :key="item.userId"
                :label="item.trueName"
                :value="item.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="s-btn">
            <el-button
              type="success"
              icon="el-icon-search"
              @click="toSearch('ruleForm')"
            >
              查询
            </el-button>
            <el-button type="success" plain @click="reset"> 重置 </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格部分 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        ref="leftTable"
        header-cell-class-name="tab-head"
        @select="selectionChange"
        height="490"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="selectAble"
        >
        </el-table-column>
        <el-table-column prop="name" label="分组名称"></el-table-column>
        <el-table-column prop="totalNumber" label="人数"></el-table-column>
        <el-table-column prop="finalCalculationStatus" label="计算状态">
          <template slot-scope="scope">
            <span>{{
              scope.row.finalCalculationStatus | calcStatusFilter
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateMethod" label="更新方式">
          <template slot-scope="scope">
            <span>{{ scope.row.updateMethod | updateWayFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="groupStatus" label="启用状态">
          <template slot-scope="scope">
            <span>{{ scope.row.groupStatus === true ? '开启' : '关闭' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdUser" label="创建人">
          <template slot-scope="scope">
            <span>{{ scope.row.createdUser.userName || '---' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-全局组件-->
      <pageCom
        :searchParams="searchParams"
        :total="total"
        @searchList="searchList"
      ></pageCom>
      <div class="notes">
        <div class="notes__zhu">注:</div>
        <div class="notes__content">
          <ul>
            <li>
              1、最多可选择5个分组，分组被选中后，在【用户分组管理】模块谨慎修改此分组条件，避免影响本条消息任务；
            </li>
            <li>
              2、自动更新且启用状态的分组用户数据动态更新，向最新计算出的用户发送消息；
            </li>
            <li>
              3、分组从未计算出用户，不向此分组发送消息，计算出用户，向最后计算出的用户发送消息（例如分组A计算人数为0，
              不向A发送消息，分组B首次计算人数不为0，第二次计算人数为0，向首次计算出的用户发消息）；
            </li>
          </ul>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="closeAddDialog"
          >取 消</el-button
        >
        <el-button
          type="success"
          :loading="confirmloading"
          @click="exportConfirm"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { getColleges } from '@/api/couponsIntegral/coupons' // 接口
import { userGroupList, enabled, disabled } from '@/api/userGroup'
import { StudentGroupFind } from '@/api/notice'
import { getUsers } from  '@/api/notice'
const updateWayDic = {
  AUTO: { text: '自动更新' },
  MANUAL: { text: '手动更新' },
}

const calcStatusDic = {
  SUCCESS: { text: '成功' },
  FAIL: { text: '失败' },
  CALCULATING: { text: '计算中' },
}

export default {
  name: 'studentGroupingDialog',
  msg: '学员分组弹窗',
  props: ['dialogData'],
  data() {
    return {
      loading: false,
      loadingRight: false,
      confirmloading: false,
      total: 0,
      totalRight: 0,
      tableData: [], // table内容
      showCheckData: [], // 已选课程
      checkData: [], // 已选课程名称
      searchParams: {
        pageNum: 1, // 当前页数
        pageSize: 10, // 页面显示条数
      },
      formInline: {
        name: '', // 用户分组名称
        groupStatus: '', // 开启状态
        finalCalculationStatus: '', // 用户分组最终计算状态
        updateMethod: '', // 用户分组更新方式
        createdUser: '', // 用户分组创建人
        groupCreationType: '', // 用户分组创建类型
      },
      creaters: [], // 创建人
      pickerOptions: {
        disabledDate(time) {
          //此条为设置禁止用户选择今天之前的日期，包含今天。
          // return time.getTime() <= (Date.now());
          //此条为设置禁止用户选择今天之前的日期，不包含今天。
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
      collegeList: [{ dictLabel: '全部学院', dictValue: '' }], // 学院名称
      stateList: [], //状态 开启:open  关闭:close
      calculationStatusList: [], //计算状态  成功:	success  失败:fail   计算中:in_calculation
      updateModeList: [], //更新方式  自动更新:automatic_update 手动更新:manual_update
      multipleSelection: [], //table选中的分组id
      selectionId: [], //存放选中分组id
      maxSize: 200,
    }
  },
  watch: {},
  filters: {
    updateWayFilter(type) {
      return updateWayDic[type].text
    },
    calcStatusFilter(type) {
      return calcStatusDic[type].text
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.checkData = this.dialogData.userGroupList
      this.selectionId = this.dialogData.selectionId
        ? [...this.dialogData.selectionId]
        : []
    })
    this.getStatusList()
    this.searchList()
  },
  methods: {
    /* 获取列表 */
    searchList() {
      this.loading = true
      let obj = Object.assign({}, this.searchParams, this.formInline)
      userGroupList(
        obj,
        (response) => {
          this.loading = false
          this.tableData = response.rows
          this.total = response.total
          this.$nextTick(() => {
            this.tableShowSelect()
          })
        },
        (response) => {
          this.loading = false
          this.$message({
            message: response.message,
            type: 'warning',
          })
        }
      )
    },
    // 搜索
    toSearch() {
      this.searchParams.pageNum = 1
      this.searchList()
    },
    /* 获取字典状态 */
    async getStatusList() {
      //状态
      let data = await sysNormalDisable(
        'student_grouping_status',
        'student_grouping_status'
      )
      this.stateList = this.stateList.concat(data)
      //计算状态 SUCCESS FAIL CALCULATING
      let data2 = await sysNormalDisable(
        'calculation_status',
        'calculation_status'
      )
      this.calculationStatusList = this.calculationStatusList.concat(data2)
      //更新方式  MANUAL AUTO
      let data3 = await sysNormalDisable('update_mode', 'update_mode')
      this.updateModeList = this.updateModeList.concat(data3)
      //创建人查询数据
      let roles = [{ id: '311' },{ id: '301' },{ id: '296' },{ id: '292' },{ id: '236' },{ id: '257' }]
      // 创建人
      await getUsers(roles, (response) => {
        this.creaters = this.creaters.concat(response)
      })
    },
    // 重置
    reset() {
      this.$refs['ruleForm'].resetFields()
    },
    // 确认导出
    exportConfirm() {
      this.$emit(
        'selectGroup',
        this.selectionId,
        this.checkData,
        this.showCheckData
      )
      this.checkData = []
      this.closeAddDialog()
    },
    // 弹窗关闭事件
    closeAddDialog() {
      this.loading = false
      this.dialogData.courseIds = []
      this.dialogData.checkData = []
      this.dialogData.isShow = false
    },
    /* 换页 */
    changePage(page) {
      this.searchParams.pageNum = page
      this.searchList()
    },
    /*手动勾选*/
    selectionChange(selection, row) {
      let curId = row.id
      if (this.selectionId.includes(curId)) {
        //已有，说明是减
        let index = this.selectionId.findIndex((item) => {
          return item == curId
        })
        if (index >= 0) {
          this.delCheck(curId, 'right')
        }
      } else {
        //没有，说明是加
        this.addCheck(row)
      }
    },
    /*增加已选课程*/
    addCheck(row) {
      this.selectionId.push(row.id)
      this.checkData.push(row)
    },
    /*减少已选课程*/
    delCheck(id) {
      let index = this.checkData.findIndex((item) => {
        return item.id == id
      })
      let indexId = this.selectionId.findIndex((item) => {
        return item == id
      })
      if (index >= 0) {
        this.checkData.splice(index, 1)
        this.selectionId.splice(indexId, 1)
        this.changeChooseLeft(id, false)
      }
    },

    /*左侧列表数据回填(删除/新增)*/
    changeChooseLeft(id, flog) {
      let index = this.tableData.findIndex((item) => {
        return item.id == id
      })
      if (index >= 0) {
        let row = this.tableData[index]
        this.$refs.leftTable.toggleRowSelection(row, flog)
      }
    },
    /*获取列表数据后，数据回填*/
    tableShowSelect(flog = true) {
      for (let [index, item] of this.tableData.entries()) {
        let id = item.id
        if (this.selectionId.includes(id)) {
          let row = this.tableData[index]
          this.$refs.leftTable.toggleRowSelection(row, flog)
        }
      }
    },
    cleanCheck() {
      this.tableShowSelect(false)
      this.checkData = []
      this.selectionId = []
      this.showCheckData = []
    },
    //判断是否可以勾选
    selectAble(row, index) {
      let isSelect = this.selectionId.includes(row.id)
      if (this.selectionId.length < 5) {
        return (
          this.totalRight < this.maxSize ||
          (this.totalRight >= this.maxSize && isSelect)
        )
      } else {
        return isSelect
      }
    },
  },
}
</script>

<style lang="less">
#dialogChooseClass {
  .clear-btn {
    float: right;
  }
  .tab-head .el-checkbox {
    display: none;
  }
  .search-box {
    padding-left: 0 !important;
    overflow: hidden;
  }
  .el-table {
    .el-button {
      padding: 0 0px;
    }
  }
  .el-form-item .el-form-item__content {
    margin-left: 0 !important;
  }
  .search-box .el-input .el-input__inner {
    padding: 0 5px 0 30px !important;
  }
  .notes {
    display: flex;
    flex-direction: row;
    color: red;
    &__content {
      padding-left: 5px;
    }
  }
}
</style>